<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索添加 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getCateList">
            <el-button slot="append" icon="el-icon-search" @click="getCateList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <tree-table
        :data="catelist"
        :columns="columns"
        :expand-type="false"
        :selection-type="false"
        show-index
        border
      >
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.level===0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.level==1">二级</el-tag>
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>

        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEdit(scope.row.id)"
          >编辑</el-button>

          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="remove(scope.row.id)"
          >删除</el-button>
        </template>
      </tree-table>

      <!-- 分页 -->

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2,5,10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <!-- 添加分类表单 -->

      <el-form ref="addCateFormRef" :model="addCateForm" label-width="80px" :rules="rule">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="addCateForm.name"></el-input>
        </el-form-item>

        <el-form-item label="父级分类">
          <!-- options数据源 -->
          <!-- props 用来指定配置对象 -->
          <el-cascader
            expand-trigger="hover"
            :options="ParentCateList"
            :props="cascaderProps"
            v-model="selectedKeys"
            @change="parentCateChanged"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>

        <el-form-item label="图片" prop="images">
          <el-input v-model="addCateForm.imageUrl" v-if="false" @input="update($event)"></el-input>
          <el-upload
            class="avatar-uploader"
            action="http://shop.cn/api/v1.Qny/upload/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" style="border: 1px dashed #d9d9d9;"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改分类的对话框 -->

    <!-- 内容主体 -->

    <el-dialog title="修改分类" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="rule" ref="editFormRef" label-width="70px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>

        <el-form-item label="图片" prop="images">
          <el-input v-model="editForm.images" v-if="false"></el-input>

          <el-upload
            class="avatar-uploader"
            action="http://shop.cn/api/v1.Qny/upload/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <!-- 有原数据就用元数据，没有就更换 -->
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <img v-else :src="editForm.images" class="avatar" />

            <!-- <i v-else class="el-icon-plus avatar-uploader-icon" style="border: 1px dashed #d9d9d9;"></i> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { server } from '../api/index'
export default {
  data() {
    return {
      queryInfo: {
        query: '',
        //当前页数
        pagenum: 1,
        //当前页显示多少条

        pagesize: 10
      },
      imageUrl: '',
      //商品分类列表
      catelist: [],
      total: 0,
      addCateDialogVisible: false,
      editDialogVisible: false,
      // 添加分类的表单数据对象
      addCateForm: {
        name: '',
        //默认一级分类
        pid: 0,
        level: 0
      },
      editForm: {},
      rule: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          {
            min: 2,
            max: 11,
            message: '长度在 2 到 11 个字符',
            trigger: 'blur'
          }
        ]
      },
      //   为table指定列的定义
      columns: [
        {
          label: '分类名称',
          prop: 'name'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      //父级分类的列表
      ParentCateList: [],
      //指定级联选择器的配置对象
      cascaderProps: {
        value: 'id',
        label: 'name',
        children: 'children'
      },
      //选中的父级分类的Id数组
      selectedKeys: []
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取商品分类数据
    async getCateList() {
      const { data: res } = await server.getCategoryList(this.queryInfo)
      if (res.code !== 200) {
        return this.$message.error('获取分类列表失败')
      }
      console.log(res)
      this.catelist = res.data.data
      this.total = res.data.total
    },
    //监听分页改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    //监听页码值
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    //点击打开添加对话框
    showAddCateDialog() {
      //先获取父级分类再展示对话框
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    //获取父级分类
    async getParentCateList() {
      const params = { type: 2 }
      const { data: res } = await server.getCategoryList(params)
      if (res.code != 200) {
        return this.$message.error('获取父级分类数据失败')
      }
      this.ParentCateList = res.data.data
      console.log(res.data)
    },
    //图片上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data
      this.addCateForm.imageUrl = res.data
      //完成后清除所有的图片
      // this.editCateForm.imageUrl == URL.createObjectURL(file.raw)
      this.editForm.imageUrl = res.data
      // console.log(res)
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type == 'image/jpeg' ||
        file.type == 'image/png' ||
        file.type == 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //选择项发生变化触发
    parentCateChanged() {
      console.log(this.selectedKeys)
      //如果selectedKeys数组中的length大于0 证明选中的父级分类
      //反之，就说明没有选中任何父级分类
      if (this.selectedKeys.length > 0) {
        //父级分类id
        this.addCateForm.pid = this.selectedKeys[this.selectedKeys.length - 1]
        //为当前分类的等级赋值
        this.addCateForm.level = this.selectedKeys.length
        return
      } else {
        //父级分类的id
        this.addCateForm.pid = 0
        //为当前分类的等级赋值
        this.addCateForm.level = 0
      }
    },
    //点击按钮，添加新的分类
    addCate() {
      console.log(this.addCateForm)
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await server.addCategory(this.addCateForm)

        if (res.code != 200) {
          return this.$message.error('添加失败,分类名可能存在了')
        }
        this.$message.success('添加成功')
        this.addCateDialogVisible = false
        this.imageUrl = ''
        this.addCateForm.imageUrl = ''
        this.getCateList()
      })
    },
    //关闭事件，表单重置
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      ;(this.selectedKeys = []), (this.addCateForm.pid = 0)
      this.addCateForm.level = 0
      this.imageUrl = ''
      this.addCateForm.imageUrl = ''
    },
    //打开修改对话框
    //展示用户编辑
    async showEdit(id) {
      // console.log(id)
      const { data: res } = await server.detailCategory(id)
      // console.log(res)
      if (res.code !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      this.editForm = res.data

      this.editDialogVisible = true
    },
    //用户修改对话框关闭
    editDialogClosed() {
      // this.imageUrl = ''
      // this.editForm.imageUrl = ''
      // this.editForm.images = ''
      // this.$refs.editFormRef.resetFields()
    },
    //修改操作
    editCateInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        //发起修改用户请求

        const { data: res } = await server.editCategory(
          this.editForm.id,
          this.editForm
        )
        if (res.code != 200) {
          return this.$message.error('编辑用户信息失败！')
        }
        //关闭对话框

        //刷新列表
        //关闭对话框
        this.editDialogVisible = false
        //刷新列表
        this.imageUrl = ''
        this.editForm.imageUrl = ''
        this.editForm.images = ''
        this.getCateList()
        //提示修改成功
        this.$message.success('编辑用户信息成功！')
      })
    },
    //删除
    remove(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delete(id)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async delete(id) {
      const { data: res } = await server.delCategory(id)

      if (res.code !== 200) {
        return this.$message.error('删除用户信息失败！')
      }
      //刷新列表
      this.getCateList()
      this.$message.success('删除用户信息成功！')
    }
  }
}
</script>
<style scoped>
.el-row {
  margin-bottom: 15px;
}
.el-cascader {
  width: 100%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>